package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam param) {
        //1. 动态构建出查询的DSL语句

        SearchRequest searchRequest = buildSearchRequst(param);

        SearchResult searchResponse = null;

        try{
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //3. 构建响应数据封装成我们需要的格式
            searchResponse = buildSearchResponse(response,param);
        }catch (Exception e){

        }

        return searchResponse;
    }

    private SearchRequest buildSearchRequst(SearchParam param) {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /**
         * 模糊匹配 过滤（属性，分类，品牌id，价格区间）
         */

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword())) ;
        }

        if (param.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }

        if(param.getBrandId()!=null&& param.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==null?true:param.getHasStock()==1));

        if(StringUtils.isNotEmpty(param.getSkuPrice())){
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");

            /**
         * 价格区间
         * 1_400/400_/_400
         */
        String[] s = param.getSkuPrice().split("_");

        if(s[0].equals("")&&!s[1].equals("")){
            //区间
           // skuPrice.gte(s[0]).lte(s[1]);
            skuPrice.lte(s[1]);

        }else if (!s[0].equals("")&&s[1].equals("")){
            skuPrice.gte(s[0]);
        }else{
            skuPrice.gte(s[0]).lte(s[1]);
        }

        boolQueryBuilder.filter(skuPrice);
    }

        //属性过滤
        if (param.getAttrs()!=null&&param.getAttrs().size()>0){
            for (String attr : param.getAttrs()) {
                //attr=1_4寸:5寸
                BoolQueryBuilder nestboolQuery = QueryBuilders.boolQuery();

                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrvalues = s[1].split(":");
                nestboolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestboolQuery.must(QueryBuilders.termQuery("attrs.attrValue",attrvalues));

                //每个属性必须生成一个nest查询

                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestboolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);


            }
        }


        /**
         * 排序，分页，高亮
         */

        if (StringUtils.isNotEmpty(param.getSort())){
            //sort=hotScore_asc/desc
            String sort = param.getSort();
            String[] s1 = sort.split("_");
            SortOrder order = s1[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;

            searchSourceBuilder.sort(s1[0],order);
        }

        //分页  pageSize=5
     if(param.getPageNum()!=null){
       searchSourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_SIZE);
       searchSourceBuilder.size(EsConstant.PRODUCT_SIZE);
     }else{
         searchSourceBuilder.from(0);
         searchSourceBuilder.size(EsConstant.PRODUCT_SIZE);
     }


        //高亮
        if(StringUtils.isNotEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<b style = 'color:red'>");
            highlightBuilder.postTags("</b>");
            highlightBuilder.field("skuTitle");
            searchSourceBuilder.highlighter(highlightBuilder);
        }



        searchSourceBuilder.query(boolQueryBuilder);

        //聚合

        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        searchSourceBuilder.aggregation(brand_agg);


        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(2);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);

        //属性聚合
        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("attr_agg", "attrs");

        //按照attrId聚合     //按照attrId聚合之后再按照attrName和attrValue聚合
        TermsAggregationBuilder attrIdAgg    = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg  = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        nestedAggregationBuilder.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);

        String s = searchSourceBuilder.toString();
        System.out.println(s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;

    }

    private SearchResult buildSearchResponse(SearchResponse response,SearchParam param) {

        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();


        List<SkuEsModel> list = new ArrayList<>();
        // 1. 返回的所有查询的商品
        if(hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {

                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
             if(StringUtils.isNotEmpty(param.getKeyword())){
                 HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                 String string = skuTitle.getFragments()[0].string();
                 skuEsModel.setSkuTitle(string);
             }
                list.add(skuEsModel);
            }
        }

        System.out.println(list);
        searchResult.setProducts(list);

        // 2. 当前商品的所有属性信息
        List<SearchResult.AttrVo>  attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attr_agg.getAggregations().get("attrIdAgg");

        if(attrIdAgg.getBuckets()!=null&&attrIdAgg.getBuckets().size()>0){
            for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
                //封装属性VO
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                //属性id
                Long keyAsString = bucket.getKeyAsNumber().longValue();
                attrVo.setAttrId(keyAsString);


                //属性名字
                ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");

                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
                attrVo.setAttrName(attrName);
                //属性所有可能的值

                ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
               //所有属性的可能值
//                List<String> collect = attrValueAgg.getBuckets().stream().map(item -> {
//                    String keyAsString1 = item.getKeyAsString();
//                    return keyAsString1;
//                }).collect(Collectors.toList());
                String attvalue = attrValueAgg.getBuckets().get(0).getKeyAsString();
                List<String> attvalues = Arrays.asList(attvalue.split(";"));
                attrVo.setAttrValue(attvalues);



                attrVos.add(attrVo);
            }
        }

        searchResult.setAttrs(attrVos);

        // 3. 当前所有商品涉及到的所有品牌信息

        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms  brand_agg = response.getAggregations().get("brand_agg");

        List<? extends Terms.Bucket> brand_aggBuckets = brand_agg.getBuckets();
        if(brand_aggBuckets!=null&&brand_aggBuckets.size()>0){
            for (Terms.Bucket brand_aggBucket : brand_aggBuckets) {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

                //设置品牌id
                String keyAsString = brand_aggBucket.getKeyAsString();
                brandVo.setBrandId(Long.parseLong(keyAsString));
                //设置品牌名字

                ParsedStringTerms  brand_name_agg = brand_aggBucket.getAggregations().get("brand_name_agg");
                String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandName(brand_name);

                //品牌图片
                ParsedStringTerms  brand_img_agg = brand_aggBucket.getAggregations().get("brand_img_agg");
                String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();

                brandVo.setBrandImg(brand_img);
                brandVos.add(brandVo);
            }
        }
        searchResult.setBrands(brandVos);

        //4. 当前商品的涉及到的所有分类信息
        ParsedLongTerms  catalog_agg =response.getAggregations().get("catalog_agg");

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //分类名字
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            List<? extends Terms.Bucket> catalog_name = catalog_name_agg.getBuckets();

            String catalog_name_key = catalog_name.get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name_key);
            catalogVos.add(catalogVo);
        }

        searchResult.setCatalogVos(catalogVos);
        // 5. 分页信息、总页码
        Long totalHits = hits.getTotalHits().value;
        searchResult.setTotal(totalHits);
        //多少页
        int totalPages = (int) (totalHits%EsConstant.PRODUCT_SIZE==0?totalHits/EsConstant.PRODUCT_SIZE:totalHits/EsConstant.PRODUCT_SIZE+1);
        searchResult.setTotalPages(totalPages);

        //当前页码
        Integer pageNum = null;
        if(param.getPageNum()!=null){
           pageNum = param.getPageNum();
        }else{
           pageNum = 1;
        }

        searchResult.setPageNum(pageNum);
        List<Integer> pageNavs=new ArrayList<>();
        for(int i=1;i<=totalPages;i++){
            pageNavs.add(i);
        }

        searchResult.setPageNavs(pageNavs);


        System.out.println(searchResult);
        return searchResult;
    }
}
